package com.zy.nettypoject.netty.demo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class TestTextLength {
    public static void main(String[] args) {

        EmbeddedChannel channel = new EmbeddedChannel(
                // 最大接受字节数，首次读取字节偏移量，内容前的长度字节，如果实际内容后还有额外的字节书，必须指定其长度约定好，将读取的长度字节偏移掉去除
               new LengthFieldBasedFrameDecoder(1024,0,2,2,2),
               new LoggingHandler(LogLevel.DEBUG)
        );

        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        stringMake(buffer, "Hello Word");
        stringMake(buffer, "FF");
        stringMake(buffer, "Yes it is");

        channel.writeInbound(buffer);
    }

    private static void stringMake(ByteBuf buffer, String str) {
        byte[] bytes = str.getBytes();
        buffer.writeInt(bytes.length);
        //该额外长度需要提前约定好
        buffer.writeByte(2);
        buffer.writeBytes(bytes);
    }
}
